import { getOrgTree } from '@/services/system/organization';
import {
  AddUser,
  DelUser,
  GetUserByPage,
  LockUser,
  getRoleList,
  updatePassword,
  updateUser,
} from '@/services/system/user';

import { GetReLoginToken } from '@/services/login/login';

import { filterTran, sortTran } from '@/utils/requestUtil';
import { PlusOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProFormSelect,
  ProFormText,
  ProFormTreeSelect,
  ProTable,
} from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, Form, Input, Modal, Switch, Tag, Transfer, Tree, message } from 'antd';
import React, { useEffect, useReducer, useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import { history, useModel } from 'umi';
import styles from './user.less';
import { roleFormInit, roleFormReducer, userFormInit, userFormReducer } from './userReducer';
const { TreeNode } = Tree;
const { Search } = Input;
// Usage of DebounceSelect
interface UserValue {
  label: string;
  value: string;
}
const LAYOUT_TYPE_HORIZONTAL = 'horizontal';
const User: React.FC<{}> = () => {
  const [userFormState, userdispatch] = useReducer(userFormReducer, userFormInit);

  const { initialState, setInitialState } = useModel('@@initialState');

  // 绑定角色信息弹框
  const [roleFormState, roledispatch] = useReducer(roleFormReducer, roleFormInit);
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [value, setValue] = useState<UserValue[]>([]);

  const [formVisit, setFormVisit] = useState(false); // 新建和编辑提示框
  const [formTitle, setFormTitle] = useState('重置密码'); // 标题
  const [confirmLoading3, setConfirmLoading3] = useState(false); //加载
  const [responsive, setResponsive] = useState(false);

  // 绑定客户信息
  const [customerData, setCustomerData] = useState<object[]>([{ id: '', name: '' }]);

  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable

  const [confirmLoading2, setConfirmLoading2] = useState(false); //编辑框的disable

  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const [treeData, setTreeData] = useState([{ title: '组织树', key: '0-0', children: [] }]);

  const [treeData1, setTreeData1] = useState([{ title: '组织树', key: '0-0', children: [] }]);

  const [formLayoutType, setFormLayoutType] = useState<FormLayout>(LAYOUT_TYPE_HORIZONTAL);
  const [grid, setGrid] = useState(true);
  const [roleList, setRoleList] = useState([]);

  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);

  const [treeAll, setTreeAll] = useState([{ title: '组织树', key: '0-0', children: [] }]);

  const genderMapColor = new Map([
    ['0', 'red'],
    ['1', 'green'],
  ]);

  const genderMap = new Map([
    ['0', '男'],
    ['1', '女'],
  ]);
  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (nextTargetKeys: string[], direction: TransferDirection, moveKeys: string[]) => {
    roledispatch({ type: 'onchange', targetKeys: nextTargetKeys });
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log('onSelect', selectedKeysValue);
    setSelectedKeys(selectedKeysValue);
    actionRef.current.reload();
  };

  // const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
  //   console.log('sourceSelectedKeys:', sourceSelectedKeys);
  //   console.log('targetSelectedKeys:', targetSelectedKeys);
  //   setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  // };
  const dataList: { key: React.Key; title: string }[] = [];
  const generateList = (data: DataNode[]) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key } = node;
      dataList.push({ key, title: key as string });
      if (node.children) {
        generateList(node.children);
      }
    }
  };

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    // debugger;
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  useEffect(() => {
    // Using an IIFE
    (async () => {
      const result = await getOrgTree();
      const roleResult = await getRoleList();
      const selectTempRoles = roleResult.data.map((item) => {
        return {
          value: item.id,
          label: item.name,
        };
      });
      setTreeData(result.data);
      setTreeAll(result.data);
      console.log(dataList, '---defaultData---');
      setExpandedKeys(['402881e581f6ca830181f6caa70f0003']);
      setTreeData1([{ value: 'parent 1', title: 'parent 1' }]);

      setRoleList(roleResult.data);
    })();
  }, []);

  const onScroll = (direction: TransferDirection, e: React.SyntheticEvent<HTMLUListElement>) => {
    console.log('direction:', direction);
    console.log('target:', e.target);
  };

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '用户名', //表头显示的名称
      dataIndex: 'name', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      title: '性别', //表头显示的名称
      search: false,
      dataIndex: 'gender', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      render: (_, record) => (
        <Tag color={genderMapColor.get(record.gender)}>{genderMap.get(record.gender)}</Tag>
      ),
    },
    {
      title: '电话', //表头显示的名称
      search: false,
      dataIndex: 'phone', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '邮箱', //表头显示的名称
      search: false,
      dataIndex: 'email', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },
    {
      title: '状态', //表头显示的名称
      search: false,
      dataIndex: 'isLocked', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      render: (text, record, index, action) => (
        <Switch
          checked={text ? true : false}
          onChange={async (checked: boolean) => {
            console.log(text, record, '---checked---');
            const arg = {
              id: record.id,
              isLocked: checked ? 1 : 0,
            };
            await LockUser(arg);
            action?.reload();
          }}
        />
      ),
    },
    {
      title: '角色',
      dataIndex: 'roleIds',
      width: 200,
      hideInTable: true,

      // request: async () => cascaderOptions,
      fieldProps: {
        options: roleList,
        showSearch: true,
        mode: 'multiple',
      },
      valueType: 'select',
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      sorter: true,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            userdispatch({ type: 'update' });
            form.setFieldsValue({
              name: record.name,
              id: record.id,
              email: record.email,
              phone: record.phone,
              gender: record.gender,
              customerId: record.customerName,
              orgId: record.orgId,
              roleIds: record.roleIds,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="updatePassword"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            setFormVisit(true);
            form2.setFieldsValue({
              name: record.name,
              id: record.id,
              customerId: record.customerId,
            });
          }}
        >
          重置密码
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            roledispatch({ type: 'setUserId', userId: record.id });
            // actionRef.current.reload();
            // setDeleteVisit(true);
            Modal.confirm({
              title: '删除用户',
              content: '确定要删除用户吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await DelUser({ id: record.id });
                actionRef.current.reload();
              },
            });

            // actionRef.current.reload();
          }}
        >
          删除
        </a>,

        // <a
        //   key="linkRole"
        //   onClick={async () => {
        //     roledispatch({ type: 'open', userId: record.id });
        //     const result = await loadTransferUserRelRoler({ id: record.id });
        //     roledispatch({
        //       type: 'loadData',
        //       rolesData: result?.data.data,
        //       targetKeys: result?.data.value,
        //     });
        //     actionRef.current.reload();
        //     // actionRef.current.reload();
        //   }}
        // >
        //   绑定角色
        // </a>,
        <a
          key="reLoin"
          onClick={async () => {
            const tokenMsg = await GetReLoginToken({ username: record.name, password: '' });

            sessionStorage.setItem('bctoken', JSON.stringify(tokenMsg.data.access_token));

            await fetchUserInfo();
            const urlParams = new URL(window.location.href).searchParams;
            history.push(urlParams.get('redirect') || '/welcome');
            return;

            // // roledispatch({
            // //   type: 'loadData',
            // //   rolesData: result?.data.data,
            // //   targetKeys: result?.data.value,
            // // });
            // // console.log(tokenMsg, '-result---');
            // // //重新设置
            // // sessionStorage.setItem('bctoken', JSON.stringify(tokenMsg.message));

            // //设置默认选项
            // const result = await GetUserInfo();

            // const currentUser = result?.data; //获取用户信息;必须要要获取用户信息

            // // const result2 = await GetUserRoleByUserId({UserId: currentUser.id});
            // const roleInfo = currentUser.roleInfos || [];
            // // const result3 = await GetPersmissionByUserId({UserId: currentUser.id});
            // const permissions = currentUser.permissionInfos || [];

            // //设置
            // await setInitialState((s) => ({
            //   ...s,
            //   currentUser: currentUser,
            //   roleInfo: roleInfo,
            //   permissions: permissions,
            // }));

            // const { query } = history.location;
            // const { redirect } = query as { redirect: string };
            // window.location.href = redirect || '/welcome';

            // actionRef.current.reload();
          }}
        >
          登录
        </a>,
      ],
    },
  ];

  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (userFormState.title == '新建用户') {
      const result = await AddUser(form.getFieldsValue());
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateUser(form.getFieldsValue());
    }
    setConfirmLoading(false);
    userdispatch({ type: 'close' });
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };

  const handleSubmit2 = async () => {
    setConfirmLoading3(true);
    await updatePassword(form2.getFieldsValue());
    setConfirmLoading3(false);
    setFormVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };

  const onGenderChange = (value: string) => {};
  const tempArr = [];
  const loop = (data: DataNode[], searchValue) => {
    let arr = [];
    for (let i = 0; i < data.length; i++) {
      const strTitle = data[i].title;
      // debugger;
      const index = strTitle.indexOf(searchValue); //判断有没有搜索的值
      if (index > -1) {
        tempArr.push({
          title: data[i].title,
          key: data[i].key,
          children: data[i].children,
        });
      }
      if (data[i].children) {
        loop(data[i].children, searchValue);
      }
    }
  };
  return (
    <div className={styles.father}>
      <div className={styles.left}>
        <Search
          style={{ marginBottom: 8 }}
          placeholder="Search"
          onSearch={(value) => {
            console.log(value, '---value----');
            if (value == null || value == '') {
              setTreeData(treeAll);
            } else {
              loop(treeAll, value);
              console.log(tempArr, '--result-');
              setTreeData(tempArr);
            }
          }}
        />

        <Tree
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          defaultExpandAll
          onSelect={onSelect}
          treeData={treeData}
        />
      </div>

      <div className={styles.right}>
        {/* <div className={styles.rightInner}> */}
        <ProTable //表格Pro组件
          headerTitle="用户查询" //表头
          size="small"
          actionRef={actionRef} //用于触发刷新操作等，看api
          rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
          revalidateOnFocus={false}
          toolBarRender={(action, { selectedRows }) => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                // console.log(selectedRows, '---选取多行----');
                // 1.清空form
                userdispatch({ type: 'create' });

                form.resetFields();
                //
              }}
              type="primary"
            >
              新建用户
            </Button>,
          ]}
          request={async (params, sort, filter) => {
            const sorters = sortTran(sort);
            const filters = filterTran(params);
            console.log(sorters, filters, filter);
            const result = await GetUserByPage({
              ...params,
              sorters: sorters,
              filters: filters.filter((item) => item.field !== 'roleIds'),
              orgId: selectedKeys[0],
            });

            console.log(result);
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
            // return  await new Promise({data:[{loginName:}], total:10, success: 0})
            // return {data:[], total:10, success: 0}
          }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
          columns={columns} //上面定义的
          scroll={{ x: 'max-content' }}
          rowSelection={{}}
        />
      </div>

      <ModalForm
        visible={userFormState.visit}
        title={userFormState.title}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            userdispatch({ type: 'close' });
          },
        }}
        layout={formLayoutType}
        grid={grid}
        rowProps={{
          gutter: [16, formLayoutType === 'inline' ? 16 : 0],
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="name"
          label="用户名"
          colProps={{ md: 12, xl: 12 }}
          rules={[{ required: true, message: '请输入你的用户名' }]}
          disabled={userFormState.createOrUpdate}
        />
        <ProFormText.Password
          name="password"
          label="密码"
          colProps={{ md: 12, xl: 12 }}
          disabled={userFormState.createOrUpdate}
        />
        <ProFormText name="email" colProps={{ md: 12, xl: 8 }} label="邮箱" />
        <ProFormText name="phone" colProps={{ md: 12, xl: 8 }} label="电话" />
        <ProFormSelect
          name="gender"
          colProps={{ md: 12, xl: 8 }}
          label="性别"
          options={[
            { label: '男', value: '0' },
            { label: '女', value: '1' },
          ]}
        />

        <ProFormTreeSelect
          name="orgId"
          label="组织"
          colProps={{ md: 12, xl: 12 }}
          placeholder="Please select"
          allowClear
          width={330}
          secondary
          // tree-select args
          fieldProps={{
            showArrow: false,
            filterTreeNode: true,
            showSearch: true,
            dropdownMatchSelectWidth: false,
            // labelInValue: true,
            autoClearSearchValue: true,
            multiple: false,
            treeNodeFilterProp: 'title',
            treeDefaultExpandAll: true,
            fieldNames: {
              label: 'title',
            },
          }}
          request={async () => treeData}
        />
        <ProFormSelect
          name="roleIds"
          label="角色"
          mode="multiple"
          placeholder="Please select"
          colProps={{ md: 12, xl: 12 }}
          options={roleList}
        />
      </ModalForm>

      <ModalForm
        visible={formVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit2}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setFormVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />

        <ProFormText
          name="password"
          label="密码"
          rules={[{ required: true, message: 'Please input your orgName!' }]}
          disabled={userFormState.createOrUpdate}
        />
      </ModalForm>
      <Modal
        title="绑定角色"
        visible={roleFormState.visit}
        confirmLoading={confirmLoading2}
        onOk={async () => {
          setConfirmLoading2(true);
          await saveRolesByUserId({
            userId: roleFormState.userData.id,
            rolesId: roleFormState.targetKeys,
          });
          actionRef.current.reload();
          setConfirmLoading2(false);
          roledispatch({ type: 'close' });
        }}
        onCancel={() => {
          roledispatch({ type: 'close' });
        }}
      >
        <Transfer
          dataSource={roleFormState.rolesData}
          titles={['未选', '已选']}
          targetKeys={roleFormState.targetKeys}
          onChange={onChange}
          onScroll={onScroll}
          render={(item) => item.title}
        />
      </Modal>
    </div>
  );
};
export default User;
